#!/usr/bin/ruby
# -*- coding: utf-8 -*-
#

require 'mysql'
require 'rexml/document'
require 'net/http'
require 'date'

require 'aws'
require '../db_setting'


$block_words = [/の著者$/, /^その他$/, /別$/, /賞$/, /^一般$/]


def db_add_node(db, id, parent_id, name, layer)

  puts "add node #{parent_id}->#{id} '#{name}' '(#{layer})"

  # add edge
  sql = 'insert into link_browse_node2browse_node (parent_id, child_id) values ' +
    "('#{parent_id}', '#{id}')"
  begin
    db.query(sql)
  rescue => exc
    puts sql
    p exc
  end

  # add node
  sql = "select * from browse_nodes where id = '#{id}'"
  res = db.query(sql)
  if res.num_rows == 0 then
    sql = 'insert into browse_nodes (id, name, layer) values ' +
      "('#{id}', '#{name.gsub(/'/, ' ')}', #{layer})"
    begin
      db.query(sql)
    rescue => exc
      puts sql
      p exc
    end

    return true
  elsif
    puts "Duplicate entry '#{sql}'"
  end
  return false
end


def update_child_nodes(db, parent_id, layer)
  while true
    res = ""
    signed_url = ""
    Net::HTTP.start(AWS_URL, 80) do |http|
      req = [
             "AWSAccessKeyId=#{AWS_ACCESS_KEY_ID}",
             "BrowseNodeId=#{parent_id}",
             "Operation=BrowseNodeLookup",
             'Service=AWSECommerceService',
             "Timestamp=#{Time.now.getgm.strftime('%Y-%m-%dT%H%%3A%M%%3A%SZ')}",
             "Version=#{AWS_VERSION}"
            ].join("&")
      signed_url = aws_signed_url(req)

      res = http.get(signed_url).body
      file = open("hoge.xml", "w")
      file.puts res
      file.close
      exit
    end

    begin
      doc = REXML::Document.new res
      ct = 0
      doc.elements.each("//Children/BrowseNode") do |node|
        ct += 1
        id = node.elements['BrowseNodeId'].text.to_i
        name = node.elements['Name'].text
        # puts "id=#{id}, name=#{name}"
    
        #       block = false
        #       $block_words.each do |word|
        #         block = true if name =~ word
        #       end
        #       if block then
        #         puts "'#{name}' is blocked"
        #         next
        #       end
    
        if db_add_node(db, id, parent_id, name, layer) then
          update_child_nodes(db, id, layer + 1)
        else
          puts "duplicate entry #{parent_id}->#{id} '#{name}' '(#{layer})"
        end
      end
      if ct == 0 then
        puts "leaf node '#{signed_url}'"
      end
    rescue => exc
      p exc
      next
    end
    break
  end
end


db = Mysql::new(DB_HOST, DB_USER, DB_PASS, DB_NAME)

update_child_nodes(db, 492356, 2)
exit


books_node_id = 465610
db_add_node(db, books_node_id, 0, "Books", 1)
update_child_nodes(db, books_node_id, 2)



# # update num_child
# res = db.query("select id from browse_node")
# res.each do |row|
#   id = row[0].to_i
#   res2 = db.query("select count(*) from browse_node where parent_id = #{id}")
#   num_child = res2.fetch_row[0].to_i
#   puts "#{id}, #{num_child}"
#   db.query("update browse_node set num_child = #{num_child} where id = #{id}")
# end

db.close
